package com.yange.accountbook.ui.adapter

import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.lxj.xpopup.XPopup
import com.yange.accountbook.R
import com.yange.accountbook.entity.AccountDetailEntity
import com.yange.accountbook.entity.IconEntity
import com.yange.accountbook.events.AccountDetailChangeEvent
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.popup.IconPopup
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.UserDao
import com.yange.accountbook.utils.showToast
import com.yanzhenjie.recyclerview.*
import org.greenrobot.eventbus.EventBus

class DetailListOneAdapter :
    BaseQuickAdapter<AccountDetailEntity.DaysDTO, BaseViewHolder>(R.layout.item_detail_one_layout) {
    override fun convert(holder: BaseViewHolder, item: AccountDetailEntity.DaysDTO) {
        holder.setText(R.id.tv_title, item.date)
        if (item.money >= 0) {
            holder.setText(R.id.tv_money, "收入" + StringUtils.getNoMoreThanTwoDigits(item.money))
        } else {
            holder.setText(
                R.id.tv_money,
                "支出" + StringUtils.getNoMoreThanTwoDigits(item.money * -1)
            )
        }
        var listview = holder.getView<SwipeRecyclerView>(R.id.data_list)
        var twoAdapter = DetailListTwoAdapter()
        var swipeMenuCreator =
            SwipeMenuCreator { leftMenu, rightMenu, position ->
                var deleteItem = SwipeMenuItem(context)
                deleteItem.height = MATCH_PARENT
                deleteItem.width = 200
                deleteItem.textSize = 12
                deleteItem.setBackground(R.color.my_red)
                context.getColor(R.color.text_white).let { deleteItem.setTextColor(it) }
                deleteItem.text = "删除"
                rightMenu?.addMenuItem(deleteItem)
            }

        if (listview.adapter == null) {
            listview.setSwipeMenuCreator(swipeMenuCreator)
            listview.setOnItemMenuClickListener(object : OnItemMenuClickListener {
                override fun onItemClick(menuBridge: SwipeMenuBridge?, adapterPosition: Int) {
                    menuBridge?.closeMenu()
                    // 左侧还是右侧菜单：
                    val direction = menuBridge!!.direction
                    // 菜单在Item中的Position：
                    val menuPosition = menuBridge.position
                    if (direction == -1 && menuPosition == 0) {
                        if (UserDao.getUserInfo().id != twoAdapter.data[adapterPosition].createBy) {
                            AlertDialog.Builder(context).setMessage("不可删除他人记录")
                                .setPositiveButton(
                                    "知道了"
                                ) { dialog, id -> }
                                .show()
                        } else {
                            XPopup.Builder(context)
                                .asConfirm(
                                    "提示", "确认删除该明细吗"
                                ) {
                                    deleteOrder(
                                        twoAdapter.data[adapterPosition],
                                        adapterPosition,
                                        twoAdapter
                                    )
                                }
                                .show()
                        }

                    }
                }
            })

        }

        //添加icon点击
        twoAdapter.addChildClickViewIds(R.id.iv_book_icon)
        twoAdapter.setOnItemChildClickListener { adapter, view, position ->

            var item = adapter.getItem(position) as AccountDetailEntity.DaysDTO.RecordsDTO
            if (null == item.icon) {
                item.icon = ""
            }
            //修改账户
            if (view.id == R.id.iv_book_icon) {
                XPopup.Builder(context)
                    .asCustom(IconPopup(context, object : IconPopup.AddListener {
                        override fun success(icon: IconEntity) {
                            update(icon, twoAdapter, position)
                        }
                    }, IconEntity(item.icon, item.name, item.id)))
                    .show()

            }
        }

        listview.layoutManager = LinearLayoutManager(context)
        listview.adapter = twoAdapter
        twoAdapter.setNewInstance(item.records)
    }


    fun deleteOrder(
        record: AccountDetailEntity.DaysDTO.RecordsDTO,
        index: Int,
        twoAdapter: DetailListTwoAdapter
    ) {
        RetrofitClient.getInstance()
            .deleteRecord(context, Api.ACCOUNT_RECORD_DELETE, listOf(record.id))
            .subscribe(object : RecObserver<BaseResponse<Any>>(context, true, false) {
                override fun onSuccess(t: BaseResponse<Any>?) {
                    showToast("删除成功")
                    twoAdapter.data.removeAt(index)
                    twoAdapter.notifyDataSetChanged()
                    EventBus.getDefault()
                        .post(AccountDetailChangeEvent(record.bookId, record.accountId))
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }

            })


    }

    private fun update(
        icon: IconEntity,
        twoAdapter: DetailListTwoAdapter, position: Int
    ) {
        RetrofitClient.getInstance().invokePostBody(
            context, Api.ACCOUNT_RECORD_UPDATE, mapOf(
                "id" to icon.bizId,
                "icon" to icon.icon,
                "name" to icon.name
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(context, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                twoAdapter.data[position].name = icon.name
                twoAdapter.data[position].icon = icon.icon
                twoAdapter.notifyDataSetChanged()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }

}